package com.flipdf.viewer.print;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.flipdf.viewer.stamp.Stamp;
import com.flipdf.viewer.stamp.TextStamp;
import com.flipdf.viewer.stamp.VariableData;
import com.lowagie.text.DocumentException;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfReader;
import com.lowagie.text.pdf.PdfStamper;

public class PDFPublisher {
	File plate;
	List<Stamp> stamps;
	List<VariableData> rows;

	public PDFPublisher(File plate, List<Stamp> stamps, List<VariableData> rows) {
		this.plate = plate;
		this.stamps = stamps;
		this.rows = rows;
	}

	public void publish() throws IOException {
		for (int i = 0; i < rows.size(); i++) {
			PdfReader reader = new PdfReader(plate.getAbsolutePath());
			VariableData row = rows.get(i);
			Map<String, String> data = row.getData();

			String path = plate.getAbsolutePath();
			path = path.substring(0, path.length() - ".pdf".length()) + "_" + i + ".pdf";

			addStamp(reader, data, path);
			reader.close();
		}
	}

	private void addStamp(PdfReader reader, Map<String, String> data, String path) {
		int n = reader.getNumberOfPages();
		PdfStamper stamp;
		try {
			stamp = new PdfStamper(reader, new FileOutputStream(path));
			HashMap moreInfo = new HashMap();
			moreInfo.put("Author", "oopdf");
			stamp.setMoreInfo(moreInfo);
			for (int i = 0; i < stamps.size(); i++) {
				TextStamp textStamp = null;
				if (stamps.get(i) instanceof TextStamp) {
					textStamp = (TextStamp) stamps.get(i);
				}

				int pageNo = 0;
				PdfContentByte over;

				while (pageNo < n) {
					pageNo++;
					over = stamp.getOverContent(pageNo);
					over.beginText();

					BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI,
							BaseFont.EMBEDDED);
					int fontsize = 16;
					over.setFontAndSize(bf, fontsize);
					over.setTextMatrix(textStamp.getRect().x, reader.getPageSize(pageNo)
							.getHeight() - fontsize
							- textStamp.getRect().y);
					over.setColorFill(textStamp.getColor());
					over.showText(data.get(textStamp.getText()));

					// over.setFontAndSize(bf, 32);
					// over.showTextAligned(Element.ALIGN_LEFT, "DUPLICATE",
					// 230,
					// 430, 45);
					over.endText();
				}
			}
			stamp.close();
		} catch (FileNotFoundException e1) {
			e1.printStackTrace();
		} catch (DocumentException e1) {
			e1.printStackTrace();
		} catch (IOException e1) {
			e1.printStackTrace();
		}
	}
}
